package com.example.smart.ui.activity.scan

import android.content.Intent
import com.alibaba.fastjson.JSON
import com.example.lib.constants.JumpConstants
import com.example.lib.extend.setOnDoubleClickListener
import com.example.lib.utils.am.ActManger
import com.example.smart.base.dialog.TipsDialog
import com.example.smart.R
import com.example.smart.base.ui.activity.BaseCameraActivity
import com.example.smart.data.AnimalData
import com.example.smart.databinding.ActivityScanFullBinding
import com.example.smart.ui.activity.animal.AddAnimalActivity
import com.example.smart.ui.activity.animal.AddAnimalQrCodeActivity
import com.example.smart.ui.m.MAddAnimalActivity
import com.example.smart.utils.DisplayUtils
import com.google.zxing.Result
import com.king.camera.scan.AnalyzeResult

class ScanFullActivity : BaseCameraActivity<ActivityScanFullBinding>() {

    private val mDialog by lazy {
        TipsDialog(this@ScanFullActivity).also {
            it.setCancelText(getString(com.example.lib.R.string.exit))
            it.setOkText(getString(com.example.lib.R.string.retry))
            it.setCancelListener { dialog ->
                dialog.dismiss()
                finish()
            }
            it.setDoneListener { dialog ->
                dialog.dismiss()
                startScan()
            }
        }
    }

    override fun layoutID() = R.layout.activity_scan_full

    override fun getPreviewView() = binding.ScanFullPreviewView

    override fun initView() {
        super.initView()
    }

    override fun initListener() {
        binding.ScanFullBack.setOnDoubleClickListener {
            finish()
        }
    }

    override fun onScanResultCallback(result: AnalyzeResult<Result>) {
        stopScan()
        val text = result.result.text
        parseQrcode(text)
    }

    private fun parseQrcode(text: String) {
        try {
            val obj = JSON.parseObject(text, AnimalData::class.java)
            val i = if (DisplayUtils.type == 0) {
                Intent(this@ScanFullActivity, AddAnimalActivity::class.java)
            } else {
                Intent(this@ScanFullActivity, MAddAnimalActivity::class.java)
            }
            i.putExtra(JumpConstants.Bean, obj)
            startActivity(i)
            ActManger.finishActivity(AddAnimalActivity::class.java)
            ActManger.finishActivity(AddAnimalQrCodeActivity::class.java)
            finish()
        } catch (ignore: Exception) {
            ignore.printStackTrace()
            mDialog.setMsg(getString(R.string.unknown_error))
            mDialog.show()
        }
    }
}